package com.ccys.app.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ccys.app.service.IndoPostConsultFlowService;
import com.ccys.common.constants.Constants;
import com.ccys.common.constants.MessageConstants;
import com.ccys.common.third.gap.GapUtil;
import com.ccys.common.third.mailGun.MailgunUtil;
import com.ccys.common.util.Kit;
import com.ccys.common.util.StringUtil;
import com.ccys.common.vo.ResponseResultApp;
import com.ccys.db.cache.SysCodeUtil;
import com.ccys.db.cache.UserUtil;
import com.ccys.db.dto.app.IndoPostConsultFlow.CancelTransactionDto;
import com.ccys.db.dto.app.IndoPostConsultFlow.IndoCheckoutDto;
import com.ccys.db.dto.app.IndoPostConsultFlow.SetPaymentMethodDto;
import com.ccys.db.dto.app.IndoPostConsultFlow.SetShippingMethodDto;
import com.ccys.db.entity.*;
import com.ccys.db.mapper.*;
import com.netflix.config.ConfigurationManager;
import com.netflix.niws.client.http.RestClient;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.binding.MapperMethod;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import software.amazon.awssdk.http.HttpStatusCode;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import static com.ccys.common.constants.CoreAppConstants.*;
import static com.ccys.common.vo.ResponseResultApp.*;


/**
 * @ClassName: IndoPostConsultFlowServiceImpl
 * @Description:
 * @Author: billyhu
 * @Date: 2024/3/4 20:49
 */
@Slf4j
@Service
public class IndoPostConsultFlowServiceImpl implements IndoPostConsultFlowService {

    @Resource
    private TblBookingDeliveryAddressMapper bookingDeliveryAddressMapper;

    @Resource
    private TblBookingMemberInfoMapper bookingMemberInfoMapper;

    @Resource
    private TblMemberDeliveryAddressMapper memberDeliveryAddressMapper;

    @Resource
    private TblBookingPrescriptionMapper bookingPrescriptionMapper;

    @Resource
    private TblMemberMapper memberMapper;

    @Resource
    private TblCountryMapper countryMapper;

    @Resource
    private TblBookingFeeMapper bookingFeeMapper;

    @Resource
    private TblBookingMapper bookingMapper;

    @Resource
    private TblBookingBenefitMapper bookingBenefitMapper;

    @Resource
    private TblPharmacyMapper pharmacyMapper;

    @Resource
    private TblPharmacyGroupMapper pharmacyGroupMapper;

    @Resource
    private TblPlanBenefitVoucherMapper benefitVoucherMapper;

    @Resource
    private TblBookingPromoCodeMapper bookingPromoCodeMapper;

    @Resource
    private TblBookingPaymentMapper tblBookingPaymentMapper;
    @Resource
    private TblBookingGoapotikPaymentLogMapper tblBookingGoapotikPaymentLogMapper;

    @Resource
    private TblBookingDeliveryMapper bookingDeliveryMapper;



    @Override
    public ResponseResultApp checkout(IndoCheckoutDto dto) {
        Kit.allParamValid(dto,"booking_id");
        JSONObject data = new JSONObject();
        JSONObject order_detail_pre_condition = new JSONObject();
        order_detail_pre_condition.put("is_waive_counsult_fee",false);
        order_detail_pre_condition.put("merchant_id",0);
        order_detail_pre_condition.put("customer_id",0);
        data.put("order_detail_pre_condition",order_detail_pre_condition);
        if(dto.getMedications().isEmpty()){
            return success(order_detail_pre_condition);
        }
        TblMemberDeliveryAddress memberDeliveryAddress = memberDeliveryAddressMapper.selectByPrimaryKey(dto.getDelivery_address_id());
        if(memberDeliveryAddress==null){
            return success(order_detail_pre_condition);
        }

        //查询当前问诊member信息
        TblBookingMemberInfo memberInfo = new TblBookingMemberInfo();
        memberInfo.setBookingId(dto.getBooking_id());
        memberInfo.setDelFlag(0);
        memberInfo = bookingMemberInfoMapper.selectOne(memberInfo);
        //查询tbl_booking_deliver_address,如果不存在则添加，如果存在则更新
        TblBookingDeliveryAddress deliveryAddress = new TblBookingDeliveryAddress();
        deliveryAddress.setBookingId(dto.getBooking_id());
        deliveryAddress.setDelFlag(0);
        deliveryAddress = bookingDeliveryAddressMapper.selectOne(deliveryAddress);

        if(deliveryAddress==null){
            //查询用户配送地址信息
            //添加tblBookingDelivery
            deliveryAddress = new TblBookingDeliveryAddress();
            deliveryAddress.setBookingId(dto.getBooking_id());
            deliveryAddress.setBookingType(1);
            deliveryAddress.setDtlId("");
        }
        deliveryAddress.setFirstName(memberDeliveryAddress.getFirstName());
        deliveryAddress.setLastName(memberDeliveryAddress.getLastName());
        deliveryAddress.setPhone(memberDeliveryAddress.getPhone());
        deliveryAddress.setPostalCode(memberDeliveryAddress.getPostalCode());
        deliveryAddress.setAddress(memberDeliveryAddress.getAddress());
        deliveryAddress.setDetailAddress(memberDeliveryAddress.getDetailAddress());
        deliveryAddress.setFloorNumber(memberDeliveryAddress.getFloorNumber());
        deliveryAddress.setCountryId(memberDeliveryAddress.getCountryId());
        deliveryAddress.setState(memberDeliveryAddress.getState());
        deliveryAddress.setLatitude(memberDeliveryAddress.getLatitude());
        deliveryAddress.setLongitude(memberDeliveryAddress.getLongitude());
        deliveryAddress.setPhoneCountryId(memberDeliveryAddress.getCountryId());
        deliveryAddress.setMemDeliveryAddressId(memberDeliveryAddress.getId());
        try {
            deliveryAddress.setPatientSelectedAt(Kit.getUtcDate());
            deliveryAddress.setPatientSelectedDeliveryDate(Kit.getUtcDate());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        if(StringUtils.isBlank(deliveryAddress.getId())){
            bookingDeliveryAddressMapper.updateByPrimaryKey(deliveryAddress);
        }else{
            bookingDeliveryAddressMapper.insertSelective(deliveryAddress);
        }

        //更新booking_Prescription信息
        String thirdIds = dto.getMedications().stream().map(IndoCheckoutDto.Medication::getId).collect(Collectors.joining(","));
        bookingPrescriptionMapper.updateStatusByIndoCheckout(1, dto.getBooking_id(), thirdIds);
        bookingPrescriptionMapper.updateStatusByIndoCheckout(0, dto.getBooking_id(), thirdIds);

        //查询每项开药处方药的数量
        List<JSONObject> products = bookingPrescriptionMapper.selectByIndoCheckout(dto.getBooking_id(), thirdIds);

        //组装查询信息
        TblMember member = memberMapper.selectByPrimaryKey(memberDeliveryAddress.getMemId());
        /**
         * {
         *                         buyer = new BuyerCheckoutInstantModel
         *                         {
         *                             email = row["booking_member_email"].ToString(),
         *                             name = row["full_name"].ToString(),
         *                             phone = row["Mem_Phone"].ToString()
         *                         },
         *                         recipient =
         *                             new RecipientCheckoutInstantModel
         *                             {
         *                                 name = row["full_name"].ToString(),
         *                                 phone = row["Mem_Phone"].ToString(),
         *                                 address = new AddressRecipientCheckoutInstantModel
         *                                 {
         *                                     address_full = $"{(string.IsNullOrWhiteSpace(row["mem_delivery_address_detail_address"].ToString()) ? "" : $"{row["mem_delivery_address_detail_address"]} ")}{row["mem_delivery_address"]} {row["state"]} {row["country_name"]}",
         *                                     latitude = row["mem_delivery_address_latitude"].ToString(),
         *                                     longitude = row["mem_delivery_address_longitude"].ToString(),
         *                                     postal_code = row["mem_delivery_postal_code"].ToString()
         *                                 }
         *                             },
         *                         products = new List<ProductCheckoutInstantModel>(),
         *                         best_combination = true,
         *                         similarmoleculeproduct = false,
         *                         multi_merchant = false,
         *                         no_range = true,
         *                         order_source = "WHC"
         *                     };
         */
        Map<String,Object> param = new HashMap();
        Map<String,Object> buyer = new HashMap<>();
        Map<String,Object> recipient = new HashMap<>();
        Map<String,Object> address = new HashMap<>();
        Map<String,Object> consultation = new HashMap<>();

        buyer.put("email",memberInfo.getMemberEmail());
        buyer.put("name",(member.getFirstName()+member.getLastName()).replaceAll("null",""));
        buyer.put("phone",member.getPhone());
        param.put("buyer",buyer);
        recipient.put("name",buyer.get("name"));
        recipient.put("phone",member.getPhone());
        address.put("address_full",StringUtils.isBlank(deliveryAddress.getDetailAddress())?"":deliveryAddress.getDetailAddress()+deliveryAddress.getAddress()+deliveryAddress.getState()+countryMapper.selectByPrimaryKey(deliveryAddress.getCountryId()).getName());
        address.put("latitude",deliveryAddress.getLatitude());
        address.put("longitude",deliveryAddress.getLongitude());
        address.put("postal_code",deliveryAddress.getPostalCode());
        recipient.put("address",address);
        param.put("recipient",recipient);
        param.put("products",products);
        param.put("best_combination",true);
        param.put("similarmoleculeproduct",false);
        param.put("multi_merchant",false);
        param.put("no_range",true);
        param.put("order_source","WHC");

        TblBooking booking = bookingMapper.selectByPrimaryKey(dto.getBooking_id());
        TblBookingFee fee = new TblBookingFee();
        fee.setBookingId(dto.getBooking_id());
        fee.setDelFlag(0);
        fee = bookingFeeMapper.selectOne(fee);

        TblBookingBenefit bookingBenefit = new TblBookingBenefit();
        bookingBenefit.setBookingId(dto.getBooking_id());
        bookingBenefit.setDelFlag(0);

        Integer aiaMember = (bookingBenefitMapper.selectCount(bookingBenefit) > 0) ? 1 : 0;
        consultation.put("product_master_id",GapUtil.getFeeId(fee.getIsSurcharge(), booking.getDoctorCountryOfResidence(), fee.getWaiveConsultationFeeFlag() > 0, aiaMember));
        consultation.put("price",fee.getWaiveConsultationFeeFlag() > 0 ? BigDecimal.ZERO:fee.getConsultationFee());
        param.put("consultation",consultation);

        String gapResult = GapUtil.getMerchant(param);
        JSONObject gapJson = null;
        try{
            gapJson = JSONObject.parseObject(gapResult);
        }catch (Exception e){
            log.error("gap转换异常",e);
        }
        //处理返回内容
        if(gapJson!=null&&gapJson.get("item")!=null){
            //如果存在merchants 添加至三方药房 2024-03-06确认不保存
            /*if(gapJson.get("Merchants")!=null){
                try {
                    List<String> phamaryList = (List<String>) gapJson.get("Merchants");
                    TblPharmacyGroup groupCondition = new TblPharmacyGroup();
                    groupCondition.setCountryId(COUNTRY_INDONESIA_ID);
                    groupCondition.setDelFlag(0);
                    TblPharmacyGroup pharmacyGroup = pharmacyGroupMapper.selectOne(groupCondition);
                    TblPharmacy condition = new TblPharmacy();
                    condition.setDelFlag(0);
                    condition.setPharmacyGroupId(pharmacyGroup.getId());
                    condition.setCountryId(COUNTRY_INDONESIA_ID);
                    condition.setType(2);
                    for (String p : phamaryList) {
                        condition.setName(p);
                        if(pharmacyMapper.selectCount(condition)<1){
                            TblPharmacy pharmacy = new TblPharmacy();
                            BeanUtils.copyProperties(condition,pharmacy);
                            pharmacyMapper.insertSelective(pharmacy);
                        }
                    }

                }catch (Exception e){
                    log.error("获取三方药房异常",e);
                }
            }*/
            data.put("merchants",new ArrayList());
            Boolean flag = false;
            for (IndoCheckoutDto.Medication m : dto.getMedications()) {
                if(m.getSelected()!=null&&m.getSelected()==1){
                    flag = true;
                }
            }
            if(flag){
                JSONObject customAddress = (JSONObject)gapJson.getJSONArray("CustomerAddress").get(0);
                String shippingResult = GapUtil.getShipping(customAddress.getInteger("CustomerId"), customAddress.getInteger("MerchantId"), "Grab Express,Gojek Delivery,Anteraja,RPX");

                if(StringUtils.isNotBlank(shippingResult)){
                    try {
                        //todo 待配置
                        String grabLogo = "";
                        String gojekLogo = "";
                        //查询当前问诊是否有可用的voucher
                        TblPlanBenefitVoucher condition = new TblPlanBenefitVoucher();
                        condition.setBenefitId(booking.getBenefitId());
                        condition.setDelFlag(0);
                        condition.setVoucherStatus(1);
                        List<TblPlanBenefitVoucher> voucherList = benefitVoucherMapper.select(condition);
                        //获取当前使用的promocode
                        /**
                         *  Code = voucherRow["PCode_delivery_voucher"].ToString(),
                         *  ShippingAmount = decimal.Parse(voucherRow["Pcode_delivery_voucher_amount"].ToString()),
                         *  ShippingMethod = voucherRow["PCode_delivery_voucher_shipping_method"].ToString()
                         */
                        TblPromoCode promoCode = bookingPromoCodeMapper.selectPromoCodeByIndoCheckout(dto.getBooking_id());
                        JSONArray shippingArr = JSONArray.parseArray(shippingResult);
                        JSONObject shippingJson;
                        TblPlanBenefitVoucher tempVoucher;
                        for (Object o : shippingArr) {
                            shippingJson = (JSONObject) o;
                            tempVoucher = null;
                            if(voucherList.isEmpty()){
                                shippingJson.put("VoucherAmount",0);
                                shippingJson.put("VoucherCode","");
                                shippingJson.put("VoucherLabel","");
                            }else{

                                for (TblPlanBenefitVoucher v : voucherList) {
                                    if(v.getVoucherIsIncludedDelivery()==1&&(
                                            v.getVoucherShippingMethod().toLowerCase().equals(shippingJson.getString("MethodTitle").toLowerCase())
                                                    ||shippingJson.getString("MethodTitle").toLowerCase().contains(v.getVoucherShippingMethod().toLowerCase())
                                                    ||"all".equals(v.getVoucherShippingMethod().toLowerCase())
                                            )
                                    ){
                                        tempVoucher = v;
                                    }
                                }
                                if(tempVoucher!=null){
                                    //判断DC AIA
                                    int planType = benefitVoucherMapper.selectPlanTypeByVoucherId(tempVoucher.getId());
                                    if(1==planType){
                                        //AIA
                                        shippingJson.put("VoucherAmount",tempVoucher.getVoucherShippingAmount());
                                        shippingJson.put("VoucherCode",tempVoucher.getVoucherCode());
                                        shippingJson.put("VoucherLabel", MessageConstants.CORPORATE_BENEFIT_APPLIED);
                                    }else if(2==planType){
                                        //DC
                                        shippingJson.put("VoucherAmount",tempVoucher.getVoucherShippingAmount());
                                        shippingJson.put("VoucherCode",tempVoucher.getVoucherCode());
                                        shippingJson.put("VoucherLabel", MessageConstants.BENEFIT_APPLIED);
                                        SysCode deliverFeeCode = SysCodeUtil.getCode("Indonesia_AIA_Delivery_Fee", "1");
                                        String deliveryFee = "20000";
                                        if(deliverFeeCode!=null){
                                            deliveryFee = deliverFeeCode.getValue();
                                        }
                                        shippingJson.put("Price",new BigDecimal(deliveryFee));
                                    }
                                }else{
                                    shippingJson.put("VoucherAmount",0);
                                    shippingJson.put("VoucherCode","");
                                    shippingJson.put("VoucherLabel","");
                                }
                                if(promoCode!=null){
                                    if(promoCode.getDeliveryVoucherShippingMethod().toLowerCase().equals(shippingJson.getString("MethodTitle").toLowerCase())
                                        ||shippingJson.getString("MethodTitle").toLowerCase().contains(promoCode.getDeliveryVoucherShippingMethod().toLowerCase())
                                            ||"all".equals(promoCode.getDeliveryVoucherShippingMethod().toLowerCase())
                                    ){
                                        shippingJson.put("VoucherAmount",promoCode.getDeliveryVoucherAmount());
                                        shippingJson.put("VoucherCode","");
                                        shippingJson.put("VoucherLabel",MessageConstants.BENEFIT_APPLIED);
                                    }
                                }
                                if("Grab Express".equals(shippingJson.getString("CarrierTitle"))){
                                    shippingJson.put("MethodTitle","Same Day");
                                    shippingJson.put("MethodDescription",MessageConstants.SAME_DAY_DELIVERY);
                                    shippingJson.put("Logo",grabLogo);
                                }else if("Gojek Delivery".equals(shippingJson.getString("CarrierTitle"))){
                                    if("GoSend - Instant".equals(shippingJson.getString("MethodTitle"))){
                                        shippingJson.put("MethodTitle","Same Day");
                                        shippingJson.put("MethodDescription",MessageConstants.SAME_DAY_DELIVERY);
                                    }else{
                                        shippingJson.put("MethodTitle","Next Day");
                                        shippingJson.put("MethodDescription",MessageConstants.NEXT_DAY_DELIVERY);
                                    }
                                    shippingJson.put("Logo",gojekLogo);
                                }else if("Anteraja".equals(shippingJson.getString("CarrierTitle"))){
                                        if("Anteraja Regular 2-4 hari".equals(shippingJson.getString("MethodTitle"))
                                            ||"Anteraja Regular".equals(shippingJson.getString("MethodTitle"))){
                                            shippingJson.put("MethodTitle","Regular");
                                            shippingJson.put("MethodDescription",MessageConstants.ANTERAJA_REGULAR_DELIVERY);
                                        }else if("Anteraja Sameday 1-2 Hari".equals(shippingJson.getString("MethodTitle"))
                                                ||"Anteraja Sameday".equals(shippingJson.getString("MethodTitle"))){
                                            shippingJson.put("MethodTitle","Same Day");
                                            shippingJson.put("MethodDescription",MessageConstants.ANTERAJA_SAME_DAY_DELIVERY);
                                        }
                                        shippingJson.put("Logo","https://anteraja.id/assets/img/Logo%20Anteraja-New-01.png");

                                }else if("RPX".equals(shippingJson.getString("CarrierTitle"))){
                                    if("RPX - Next Day".equals(shippingJson.getString("MethodTitle"))){
                                        shippingJson.put("MethodTitle","Next Day");
                                        shippingJson.put("MethodDescription",MessageConstants.RPX_NEXT_DAY_DELIVERY);
                                    }else if("RPX Regular".equals(shippingJson.getString("MethodTitle"))){
                                        shippingJson.put("MethodTitle","Regular");
                                        shippingJson.put("MethodDescription",MessageConstants.RPX_REGULAR_DELIVERY);
                                    }
                                    shippingJson.put("Logo","https://www.rpxonline.com/wp-content/uploads/2019/11/cropped-RPX.png");
                                }else{
                                    shippingJson.put("Logo",gojekLogo);
                                }
                            }
                        }
                        data.put("shipping_methods",shippingArr);
                        data.put("is_success",true);
                        order_detail_pre_condition.put("is_waive_counsult_fee",fee.getWaiveConsultationFeeFlag());
                        order_detail_pre_condition.put("merchant_id",((JSONObject)gapJson.getJSONArray("Items").get(0)).get("MerchantId"));
                        order_detail_pre_condition.put("customer_id",customAddress.getInteger("CustomerId"));
                        data.put("order_detail_pre_condition",order_detail_pre_condition);
                        return success(data);
                    }catch (Exception e){
                        log.error("转换gap返回shopping信息异常",e);
                    }
                }
            }
        }else if(gapJson!=null&&gapJson.get("Item")==null&&gapJson.getJSONArray("BestCombination").isEmpty()){
            order_detail_pre_condition.put("is_waive_counsult_fee",fee.getWaiveConsultationFeeFlag());
            try {
                order_detail_pre_condition.put("merchant_id",((JSONObject)gapJson.getJSONArray("Items").get(0)).get("MerchantId"));
                order_detail_pre_condition.put("customer_id",((JSONObject)gapJson.getJSONArray("CustomerAddress").get(0)).getInteger("CustomerId"));

            }catch (Exception e){

            }
            data.put("order_detail_pre_condition",order_detail_pre_condition);
            return success(data);
        }else{
            order_detail_pre_condition.put("is_waive_counsult_fee",fee.getWaiveConsultationFeeFlag());
            order_detail_pre_condition.put("merchant_id",0);
            order_detail_pre_condition.put("customer_id",0);
            data.put("order_detail_pre_condition",order_detail_pre_condition);
            return success(data);
        }

        return error();
    }

    @Override
    public ResponseResultApp setShippingMethod(SetShippingMethodDto dto) {
        //Todo: Get note
        //logger.Info($"IndonesiaSetShippingMethod {JsonConvert.SerializeObject(model)}");
        //var consultation = GetConsultFee(model.BookingId);
        return success();

    }

    @Override
    public ResponseResultApp getPaymentMethods(String customerId) {
        String paymentMethods = GapUtil.getPaymentMethods(customerId);
        if (StringUtil.isEmpty(paymentMethods)){
            return  ResponseResultApp.error(400, "ErrorString.BAD_REQUEST");
        }
        return success();
    }

    @Override
    @Transactional
    public ResponseResultApp setPaymentMethod(String customerId, SetPaymentMethodDto dto) {
        TblMember curLoginMember = UserUtil.getCurLoginMember();
        String memberId = curLoginMember.getId();
        if (StringUtil.isEmpty(dto.getDelivery_contact_number())) {
            String phone = this.bookingDeliveryAddressMapper.getDeliveryAddressPhone(dto.getBooking_id(),memberId);
            if (StringUtil.isEmpty(phone)) {
                return error("parameter delivery_contact_number void");
            }
            dto.setDelivery_contact_number(phone);
        }

        if (dto.getDelivery_phone_country_id() == null) {
            dto.setDelivery_phone_country_id(Constants.COUNTRY_INDONESIA_ID);
        }

        // check booking & cancel previous transaction before setting new payment
        checkBookingIsSetPayment(dto.getBooking_id());

        // set payment
        String response = GapUtil.setPaymentMethod(customerId, dto.getPayment_code(), dto.getDelivery_contact_number());
        if (StringUtil.isNotEmpty(response)) {
            //TODO 解析三方响应数据
            String payementDetail = GapUtil.getPaymentDetail("response.MaskId.Value");
            String shippingMethod = getShippingMethod(dto.getBooking_id());
            //response.PaymentDetail = payementDetail;
            TblBookingPayment tblBookingPayment = new TblBookingPayment();
            tblBookingPayment.setCustomerId(customerId);
            tblBookingPayment.setBookingId(dto.getBooking_id());
            tblBookingPayment.setPaymentMethodCode(dto.getPayment_code());
            tblBookingPayment.setRequestTime(new Date());
            tblBookingPayment.setResponseJsonString(response);
            tblBookingPayment.setPaymentDetailJson(payementDetail);
            //TODO
            tblBookingPayment.setMerchantName("payementDetail.SalesOrder.MerchantName");
            //TODO
            tblBookingPayment.setShippingMethod(StringUtil.isNotEmpty(shippingMethod)? shippingMethod:"payementDetail.SalesOrder.ShippingDescription");
            //原字段 MaskId,UniquePayment  未用上

            //原逻辑  将TblBookingPayment 数据 复制到 tbl_Booking_GoApotik_Payment_Logs 中 并不更新最新的数据到log
            TblBookingPayment tblBookingPaymentSource = this.tblBookingPaymentMapper.getBookingPaymentByBookingId(dto.getBooking_id());
            TblBookingGoapotikPaymentLog tblBookingGoapotikPaymentLog = new TblBookingGoapotikPaymentLog();
            BeanUtils.copyProperties(tblBookingPaymentSource, tblBookingGoapotikPaymentLog);
            this.tblBookingGoapotikPaymentLogMapper.insertSelective(tblBookingGoapotikPaymentLog);
            //删除原 TblBookingPayment 数据
            TblBookingPayment tblBookingPaymentDel = new TblBookingPayment();
            tblBookingPaymentDel.setBookingId(dto.getBooking_id());
            this.tblBookingPaymentMapper.delete(tblBookingPaymentDel);
            TblBooking tblBookingUpdate = new TblBooking();
            tblBookingUpdate.setId(dto.getBooking_id());
            //tblBookingUpdate.setUnique_payment
            tblBookingUpdate.setReactivateConsult(0);
            tblBookingUpdate.setUpdatedOnUtc(System.currentTimeMillis());
            this.bookingMapper.updateByPrimaryKeySelective(tblBookingUpdate);
            //统计bookingid 处方状态为1 的数据 大于0 根据booking条件更新 tbl_booking_delivery 快递类型  booking_delivery_type 为 2
            Integer count = this.bookingPrescriptionMapper.countBookingPrescription(dto.getBooking_id());
            if(count > 0) {
                TblBookingDelivery bookingDeliveryUpdate = new TblBookingDelivery();
                bookingDeliveryUpdate.setDeliveryType("2");
                Example example = new Example(TblBookingDelivery.class);
                		example.createCriteria().andCondition("del_flag=0").andCondition("booking_id = '"+dto.getBooking_id()+"'");
                this.bookingDeliveryMapper.updateByExampleSelective(bookingDeliveryUpdate,example);
            }

            if(StringUtil.isNotEmpty("payementDetail.SalesQuote.UniquePayment")) {
                TblBookingFee tblBookingFeeUpdate = new TblBookingFee();
                //TODO 更新印尼流程中,GAP返回的唯一编码
                tblBookingFeeUpdate.setPaymentVendor("payementDetail.SalesQuote.UniquePayment");
                tblBookingFeeUpdate.preUpdate();
                Example example = new Example(TblBookingFee.class);
                example.createCriteria().andCondition("del_flag=0").andCondition("booking_id = '"+dto.getBooking_id()+"'");
                this.bookingFeeMapper.updateByExampleSelective(tblBookingFeeUpdate,example);
            }
            //更新处方数据 查看三方返回是否有 处方价格
            /*TblBookingPrescription bookingPrescriptionUpdate = new TblBookingPrescription();
            bookingPrescriptionUpdate.setThirdPartyProductPrice();
            bookingPrescriptionUpdate.setUpdatedOnUtc(System.currentTimeMillis());
            this.bookingPrescriptionMapper.updateByExampleSelective();*/
            //插入 新的数据到 TblBookingPayment
            tblBookingPayment.preInsert();
            this.tblBookingPaymentMapper.insert(tblBookingPayment);

            // upload prescription image to goapotik
            uploadPrescriptionToGoApotik(memberId, dto.getBooking_id(), "response.MaskId.Value");

            //TODO 待续
            /*//WC-4298 refetch grand total for AIA ID
            response.GrandTotal = GetGrandTotalForAiaCorporateIndo(model.BookingId, response.GrandTotal);
            //End WC-4298

            //direct corporate
            UpdateClaimForDirectCorporateIndo(memId, model.BookingId);

            // update delivery address in database
            bookingHelper.UpdateDeliveryAddressForIndonesian(model.BookingId, model.DeliveryContactNumber, model.DeliveryPhoneCountryId);

            // GAP wont update status for partner_payment
            // So we have to call api updateorderstatus
            if (needUpdateStatus)
            {
                var updateStatusResponseModel = indonesiaHelper.UpdateOrderStatus(customerId, response.MaskId.Value, model.BookingId);
                if (updateStatusResponseModel != null)
                    NotificationToPatient(updateStatusResponseModel);
            }*/

            return success(response);
        } else {
            //ErrorCodes.GENERAL_FAILUR
            return error("ErrorString.GENERAL_FAILUR");
        }
    }
    public void uploadPrescriptionToGoApotik(String memberId, String bookingId, String incrementId) {
        //TODO
        // Just send when patient select the medication
        /*boolean isSend = indonesiaHelper.CheckValidateUploadPrescription(bookingId);
        // upload prescription image to goapotik
        if (isSend) {
            CompletableFuture.runAsync(() -> {
                var imageBytes = document_BL.GeneratePrescriptionPDF(HostingEnvironment.MapPath(Constants.EMAIL_TEMPLATE_PATH.API_PRESCRIPTION_PDF), memberId, bookingId, true);
                var imageBase64 = string.Format("data:image/png;base64,{0}", Common.convertToBase64(imageBytes));
                indonesiaHelper.UploadPrescriptionToGoApotik(bookingId, incrementId.ToString(), imageBase64);
            });

        }*/
    }


    // check booking & cancel previous transaction before setting new payment
    public boolean checkBookingIsSetPayment(String bookingId) {
        Map<String,Object> dsResult = this.tblBookingPaymentMapper.checkBookingIsSetpayment(bookingId);

        Integer isSetPayment = dsResult.get("resultState") == null ? 0 : Integer.parseInt(dsResult.get("resultState").toString());
        if(isSetPayment == null) {
            isSetPayment = 0;
        }
        if (isSetPayment > 0) {
            String incrementId = dsResult.get("increment_id").toString();
            String  customerId = dsResult.get("customer_id").toString();
            String reason = "cancel transaction";
            CancelTransactionDto cancelTransactionDto = new CancelTransactionDto();
            cancelTransactionDto.setBooking_id(bookingId);
            cancelTransactionDto.setCustomer_id(customerId);
            cancelTransactionDto.setReason(reason);
            cancelTransactionDto.setIncrement_id(incrementId);
            cancelTransaction(cancelTransactionDto);
        }
        return isSetPayment > 0;
    }

    public void cancelTransaction(CancelTransactionDto model) {
        if (StringUtil.isEmpty(model.getIncrement_id())) {
            model.setIncrement_id(getOrderPendingPayment(model.getBooking_id(),model.getCustomer_id()));
        }
        if (StringUtil.isEmpty(model.getIncrement_id())) {
            GapUtil.cancelTransaction(model.getIncrement_id(),model.getCustomer_id(),model.getReason());
        }

    }

    public String getOrderPendingPayment(String bookingId, String customerId) {
        //bookingId  写日志用
        String orderPendingPayment = GapUtil.getOrderPendingPayment(customerId);
        //TODO 将响应的 字符串转json  从里面取出  increment_id   没有数据可以测试响应模型 印度尼西亚 开药环节卡住了
        return orderPendingPayment;
    }


    public String getShippingMethod(String bookingId){
        String shippingOutput = "";
        /**
         * 原  执行sql
         SELECT
         top 10 request_payload
         FROM
         tbl_Third_Party_Logs
         WHERE
         booking_id = @booking_id
         AND method_name = 'SetShipping'
         AND status_code = 'OK'
         ORDER BY
         requested_on DESC;


         SELECT
         top 1 response
         FROM
         tbl_Third_Party_Logs
         WHERE
         booking_id = @booking_id
         AND method_name = 'GetShipping'
         AND status_code = 'OK'
         ORDER BY
         requested_on DESC;
         */

        // 原执行sql方法  GET_SHIPPING_METHOD
        Object dsResult = null; //sql 查询结果
        if (dsResult != null) {
            //TODO  tbl_Third_Party_Logs  表不存在 已上报 待需求确认 2024-03-08
            /*var rowSetShipping = dsResult.Tables[0].Rows[0];
            var rowGetShipping = dsResult.Tables[1].Rows[0];
            var requestPayload = rowSetShipping["request_payload"].ToString();
            var jsonRequestPayload = JsonConvert.DeserializeObject<Dictionary<string, string>>(requestPayload);
            var shippingId = jsonRequestPayload["shipping_id"];
            var responseGetShipping = rowGetShipping["response"].ToString();
            var dataGetShipping = JsonConvert.DeserializeObject<IndonesiaGeneralResponseModel<List<IndonesiaGetShippingResponseModel>>>(responseGetShipping);
            var shipping = dataGetShipping.Data.FirstOrDefault(x => x.Id.Equals(int.Parse(shippingId)));
            if (shipping.CarrierTitle == "Grab Express") {
                shippingOutput = "Grab (Same Day)";
            } else if (shipping.CarrierTitle == "Gojek Delivery")  {
                if (shipping.MethodTitle == "GoSend - Instant" || shipping.MethodTitle == "GoSend Instant") {
                    shippingOutput = "Gojek (Same Day)";
                } else {
                    shippingOutput = "Gojek (Next Day)";
                }
            }
            else if (shipping.CarrierTitle == "Anteraja")  {
                if (shipping.MethodTitle == "Anteraja Regular 2-4 hari" || shipping.MethodTitle == "Anteraja Regular") {
                    shippingOutput = "Anteraja (Regular)";
                } else if (shipping.MethodTitle == "Anteraja Sameday 1-2 Hari" || shipping.MethodTitle == "Anteraja Sameday")  {
                    shippingOutput = "Anteraja (Same Day)";
                }
            }
            else if (shipping.CarrierTitle == "RPX") {
                if (shipping.MethodTitle == "RPX - Next Day") {
                    shippingOutput = "RPX (Next Day)";
                } else if (shipping.MethodTitle == "RPX Regular")  {
                    shippingOutput = "RPX (Regular)";
                }
            }*/
        }

        return shippingOutput;

    }

}
